<template>
  <div class="fileUpload">
    <a-upload v-model:file-list="fileList" :before-upload="beforeUpload" 
      :custom-request="(file: otherType) => handleUpload(file)" @remove="removeFile" :multiple="true" v-if="props.showCard"
      :progress="progress">
      <div>
        <a-button class="upload_button_line" :disabled="props.maxCount?fileList.length >= props.maxCount:false">
          <upload-outlined></upload-outlined>
          <span class="iconfont icon-upload">
          </span> 上传文件
        </a-button>
        <!-- <div class="tips" v-if="props.accept">支持{{ props.accept }}格式</div> -->
      </div>
    </a-upload>
    <div class="middle-box" v-if="!props.isInDialog">
      <draggable :list="fileList" ghost-class="eghost" handle=".move" filter=".forbid" :force-fallback="true"
        chosen-class="chosenClass" animation="300" @start="onStart" @end="onEnd" sort="true" :fallback-class="true"
        dragClass="dragClass" :fallback-on-body="true" :touch-start-threshold="50" :fallback-tolerance="50" :move="onMove"
        class="drag-box">
        <template #item="{ element, index }">
          <div class="uploadList">
            <!-- <div class="edit-item uploadList"> -->
            <span class="upload-span">
              <a target="_blank" v-if="index !== fileIndex || !isEditFileName" class="fileName" :title="element.oriFileName || element.filename">{{
                element.oriFileName || element.filename }}</a>
                <a-input
                v-if="fileIndex === index && element.oriFileName && isEditFileName"
                  class="fileName"
                  style="background-color: transparent;width:100px"
                  v-model:value="element.oriFileName"
                  :maxlength="50"
                ></a-input>
                <a-input
                v-if="fileIndex === index && !element.oriFileName && isEditFileName"
                  class="fileName"
                  style="background-color: transparent;width:100px"
                  v-model:value="element.filename"
                  :maxlength="50"
                ></a-input>
                <span v-if="fileIndex === index && isEditFileName" class="save-btn" type="primary" @click="saveFileName(element,index)">保存</span>
                <span v-if="fileIndex !== index && !isEditFileName || !isEditFileName" class="delete-item" @click.stop.prevent="editFileName(index)">
                <i class="iconfont icon-edit" style="font-size: 16px;margin-left:0">
                </i>
              </span>
              <span v-if="fileIndex !== index && !isEditFileName || !isEditFileName" class="delete-item" @click.stop.prevent="removePictrues(element)">
                <i class="iconfont" style="font-size: 16px;margin-left:0">&#xe8e2;
                </i>
              </span>
            </span>
            <span class="move drag_move">
              <i class="iconfont"> &#xe90d;</i>
            </span>
          </div>
        </template>
      </draggable>
    </div>
    <div v-else></div>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, computed, nextTick, onMounted, reactive } from "vue";
import { message } from "ant-design-vue";
import { baseUploadProps } from "./uploadConfig/props";
import { dataSourceType } from "../../type";
import { request as $axios } from "@/api/axios";
import draggable from "vuedraggable";
import request from "@/api/index";
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
//props
const props = defineProps(baseUploadProps);
//emit
const emit = defineEmits([
  "uploadChangeFinished",
  "uploadFinished",
  "upload_remove_Finished",
  "setFileSecret",
  "draggChangeFinished",
  "fileNameChange"
]);
//type
type otherType = {
  [propName: string]: any;
};
//data
const fileIndex = ref<any>(null);
const isEditFileName = ref<Boolean>(false);
const fileList = ref<dataSourceType[]>([]);
let acceptTypeList = ref<string[]>([]);
let styles = ref<string>("");
const pp = ref<string | number>(0);
const fileData = ref<any>([]);
const contentSecretIsOpen = ref<any>('');
const progress = reactive({
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068',
  },
  strokeWidth: 3,
  format: (percent: number) => {
    return `${parseFloat((+percent).toFixed(0))}%`;
  },
  class: 'test',
});
// watch
watch(() => props.dislogVisible, (newVal, oldVal) => {
    fileData.value = []
})
watch(
  () => props.fileList,
  (newVal, oldVal) => {
    if (newVal.length) {
      // console.log(newVal, 'newVal')
      fileList.value = JSON.parse(JSON.stringify(newVal));
      fileData.value = JSON.parse(JSON.stringify(newVal));
      console.log(fileData.value, 'fileData.value');
      // nextTick(() => {
      //   getImageStyle(newVal[0].url);
      // })

      fileList.value.forEach((item: any) => {
        if (!item.contentSec) {
          item.contentSec = undefined
        }
      })

    } else {
      fileList.value = [];
      fileData.value = [];
    }
  },
  { deep: true, immediate: true }
);
//methods
const removePictrues = (info: any) => {
  fileData.value.map((item: any, index: any) => {
    if (info.id == item.id) {
      fileData.value.splice(index, 1);
    }
  });
  //
  emit("upload_remove_Finished", info);
};
const removeFile = (info: any) => {
  fileData.value.map((item: any, index: any) => {
    if (info.originFileObj.uid == item.id) {
      fileData.value.splice(index, 1);
    }
  });
  //
  emit("upload_remove_Finished", info);
};
const beforeUpload = (file: otherType["fileList"][number]) => {
  // 文件上传之前的限制条件过滤，有文件类型和文件大小限制。
  return new Promise((resolve, reject) => {
    // beforeUpload必须使用promise 返回false才能阻止change事件，否则无效
    const backgFix = file.name.substring(file.name.lastIndexOf(".") + 1); //获取文件的后缀
    let isFileType = true;
    if (acceptTypeList.value.length) {
      isFileType = acceptTypeList.value.includes(backgFix);

      if (!isFileType) {
        message.error(`只能上传${acceptTypeList.value.join(",")}格式文件!`);
        return false;
      }
    }

    let isLt2M = true;
    if (props.isLimit) {
      isLt2M =
        props.isLimit == 0 ? true : file.size / 1024 / 1024 < props.isLimit;
      if (!isLt2M) {
        message.error(`文件大小不得超过 ${props.isLimit} MB!`);
        return false;
      }
    }

    if (isFileType && isLt2M) {
      //fileList.value = [...fileList.value, file]
      return resolve(true);
    }
  });
};
// 拖拽附件排序
const onEnd = () => {
  fileData.value = JSON.parse(JSON.stringify(fileList.value));
  emit("draggChangeFinished", fileData.value);
};
const getImageStyle = (src: string) => {
  const url = src;
  if (url) {
    var img = new Image();
    img.src = url;
    img.onload = function () {
      if (img.naturalWidth >= img.naturalHeight) {
        styles.value = `width:100%;height:auto`;
      } else {
        styles.value = `width:auto;height:100%`;
      }
    };
  }
};

const editFileName = (val: any) => {
  isEditFileName.value = true;
  fileIndex.value = val;
};
// 保存附件名
const saveFileName = (ele: any,val: any) => {
  isEditFileName.value = false;
  fileIndex.value = val;
  emit('fileNameChange', fileList.value)
  const params = {
    id: ele.id,
    oriFileName: ele.oriFileName || ele.filename,
  }
  request.updateOriName(params).then((res: any) => {
    if(res.code === "00000 00000") {
      message.success(res.message)
    }else {
      message.error(res.message)
    }
  }).catch((err: any) => {
    throw new Error(err)
  })
};
const handleUpload = (options: otherType) => {
  // 上传到服务器
  const param = new FormData(); // 创建form对象
  param.append("files", options.file, options.file.name); // 通过append向form对象添加数据
  
  if (props.isAutoUpload) {
    // props.isAutoUpload 用来判断是否能直接上传，若不能，需要用emit传递出formData数据到调取处

    options.file.status = "success";

    // 要放在global
    $axios
      .post("/server-admin/res/upload", param, {
        headers: {
          "Content-Type":
            "multipart/form-data; boundary=----WebKitFormBoundary1kBB8pgsKICPa9RM",
        },
        onUploadProgress: ({ total, loaded }) => {
          if (total) {
            pp.value =
              Math.round((loaded / total) * 100) < 100
                ? Math.round((loaded / total) * 100).toFixed(1)
                : (100 - Math.random() * 10).toFixed(1);
            if (options.onProgress) {
              //留足大图片渲染时间
              options.onProgress(
                { percent: Math.round((loaded / total) * 100).toFixed(2) },
                options
              );
            }
          }
        },
      })
      .then((res: any) => {
        if (res.data.code == "00000 00000") {
          pp.value = 100;
          if (options.onSuccess) {
            options.onSuccess(res.data.data, options);
          }

          emit("uploadChangeFinished", ...res.data.data);
          message.success(res.data.message);
        } else {
          message.error(res.data.message);
          if (options.onError) {
            options.onError(res.data.data, options);
          }
          fileList.value = [];
        }
      })
      .catch((err) => {
        console.log(err, 9999);
      });
  } else {
    getBase64(options.file).then((res: any) => {
      let obj = {
        id: options.file.uid,
        url: res,
        file: options.file,
        options:options,
        isAnnex: true,
      };
      if (fileData.value.length < props.maxCount) {
        fileData.value.push(obj);
      }
      emit("uploadChangeFinished", fileData.value);
    });
  }
};
const getcontentSecret = async () => {
  contentSecretIsOpen.value = await request.getcontentSecret();
}
// 添加附件密级
const setFileSecret = (index: number) => {
  nextTick(() => {
    emit('setFileSecret', fileList.value[index].id, fileList.value[index]);
  })


}
// computed
acceptTypeList = computed({
  get() {
    return props.accept ? props.accept.split(",") : [];
  },
  set() { },
});
//onMounted
onMounted(() => {
  getcontentSecret();
})
</script>
<style lang="scss" scoped>
.ant-upload-list {
  width: 104px;
}

.fileUpload {
  ::v-deep(.ant-upload-text-icon) {
    display: none;
  }
}

.middle-box {
  max-width: 260px;
  display: flex;
  flex-wrap: wrap;
  -moz-user-select: none;
  /* Firefox私有属性 */
  -webkit-user-select: none;
  /* WebKit内核私有属性 */
  -ms-user-select: none;
  /* IE私有属性(IE10及以后) */
  -khtml-user-select: none;
  /* Khtml内核私有属性 */
  -o-user-select: none;
  /* Opera私有属性 */
  user-select: none;

  /* CSS3属性 */
  .uploadList {
    margin-top: 16px;
    display: flex;
    max-width: 274px;
    min-width: fit-content;
    width: fit-content;
    position: relative;

    .upload-span {
      width: 170px;
      display: flex;
      align-items: center;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      height: 32px;
      margin-right: 8px;

      padding: 0 8 0 16px;

      &:hover {
        .delete-item {
          display: block;
          width: 20px;

        }
        .save-btn {
          display: block;
          width: 25px;
        }
      }

      .delete-item {
        display: none;
        cursor: pointer;
      }
      .save-btn {
        margin-right: 8px;
          display: none;
          width: 25px;
          font-size: 10px;
          background-color: #1f6ded;
          color: #fff;
          border-radius: 2px;
          text-align: center;
          cursor: pointer;
        }

      .fileName {
        flex: 1;
        margin-left: 3px;
        margin-right: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        border: none;
        cursor:auto;
      }
      .ant-input:focus, .ant-input-focused {
          box-shadow:none;
        }
      .iconfont {
        color: rgba(0, 0, 0, 0.45);

        &:hover {
          color: rgba(0, 0, 0, 0.85);
        }
      }
    }

    .drag_move {
      top: -4px;
      right: 1px;

      .iconfont {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        cursor: pointer;

        &:hover {
          color: rgba(0, 0, 0, 0.65);
        }

        &:active {
          color: rgba(0, 0, 0, 0.85);
        }
      }
    }
  }
}

.eghost {}

.chosenClass {
  display: flex;
  width: fit-content;
  max-width: 260px;
  overflow: hidden;


  .upload-span {
    width: 120px;
    display: flex;
    align-items: center;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    height: 32px;
    margin-right: 8px;

    padding: 0 8 0 16px;

    &:hover {
      .delete-item {
        display: block;
        width: 20px;

      }
    }

    .delete-item {
      display: none;
      cursor: pointer;
    }

    .fileName {
      flex: 1;
      margin-left: 3px;
      margin-right: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

  }




}
</style>
<style lang="scss">
.fileUpload {
  .ant-progress-text {
    position: absolute;
    top: -5px;
    right: 25px;
  }
}

</style>
